﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;
using System.Reflection;
using AMStudio.Script;
using System.Data;

namespace AMStudio.Common
{
    public static class LanguageDB
    {
        private static LanguageTagDAL db = new LanguageTagDAL();

        public static Hashtable UIDBTags;

        public static void Init()
        {
            try
            {
                UIDBTags = db.SelectAllMapper();
            }
            catch (Exception ex)
            {
                throw new Exception("LanguageDB Init Error:" + ex.Message);
            }
        }

        public static void SaveItemChange(string UIName, string controlName, LanguageItem item)
        {
            lock (UIDBTags.SyncRoot)
            {
                string keyName = UIName + "." + controlName;
                if (item == null)
                {
                    if (UIDBTags[keyName] != null)
                    {
                        db.Delete(UIName, controlName);
                        UIDBTags.Remove(keyName);
                    }
                    return;
                }
                if (UIDBTags[keyName] != null)
                {
                    db.Update(item);
                }
                else
                {
                    db.Add(item);
                    UIDBTags.Add(keyName, item);
                }
            }
        }

        public static Dictionary<string, LanguageItem> GetUIRefreshItems(string UIName)
        {
            Dictionary<string, LanguageItem> result = new Dictionary<string, LanguageItem>();
            foreach (DictionaryEntry d in UIDBTags)
            {
                LanguageItem item = d.Value as LanguageItem;
                if (item.UIName == UIName)
                {
                    result.Add(item.ControlName, item);
                }           
            }
            return result;
        }

        public static StringValueList<LanguageItem> GetRefreshItemsForUI(string UIName)
        {
            StringValueList<LanguageItem> result = new StringValueList<LanguageItem>();
            foreach (DictionaryEntry d in UIDBTags)
            {
                LanguageItem item = d.Value as LanguageItem;
                if (item.UIName == UIName)
                {
                    result.Add(item);
                }
            }
            return result;
        }

        public static void DeleteItem(LanguageItem item)
        {
            string keyName = item.UIName + "." + item.ControlName;
            if (UIDBTags[keyName] != null)
            {
                db.Delete(item.UIName, item.ControlName);
                UIDBTags.Remove(keyName);
            }
            return;
        }
    }
}
